<template>
  <el-form ref="formRef" class='config-form' :model="model" v-bind="$attrs">
    <!-- 动态渲染表单项 -->
    <div v-for="(item, i) in formItems" :key="i">
      <el-form-item v-if="item.vIf === undefined || item.vIf" :label="item.label" :prop="Array.isArray(item.key) ? item.key[0] : item.key" v-bind="item.attrs">
        <!-- 文本类型展示 -->
        <template v-if="item.type === 'text'">
          {{model[item.key]}}
        </template>
        <!-- 动态组件渲染 -->
        <component v-else :is="componentsObj[item.type]" :form-item="item" :model="model"></component>
      </el-form-item>
    </div>
    <!-- 查询/重置按钮区域 -->
    <el-form-item v-if="isQueryArea">
      <el-button type="primary" @click="formSubmit()">查询</el-button>
      <el-button @click="formReset()">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, defineProps, PropType } from 'vue'
import type { FormInstance } from 'element-plus'
defineOptions({
  name: 'configForm'
})
// 包装功能组件
const componentsObj = ref<any>({})
const componentsFiles:any  = import.meta.glob('./components/*.vue', { eager: true })
Object.keys(componentsFiles).forEach(fileName => {
  const name:any = componentsFiles[fileName].default.__name
  componentsObj.value[name] = componentsFiles[fileName].default
})
const formRef = ref<FormInstance>()
const props = defineProps({
  // 透传至Form,用户数据
  model: {
    type: Object as PropType<Record<string, any>>,
    default: () => {}
  },
  // formItem的表单配置
  formItems: {
    type: Array as PropType<Array<Record<string, any>>>,
    default: () => []
  },
  // 纵列展示
  column: {
    type: Number,
    default: null
  },
  // 是否需要查询/重置按钮
  isQueryArea: {
    type: Boolean,
    default: true
  }
})
// 定义组件触发的事件
const emits = defineEmits<{
  (event: 'validationError', errMessage: any): void;
  (event: 'search', result: { formDatas: Record<string, any> } | false): void;
  (event: 'reset'): void;
}>()
// 查询
const formSubmit = async () => {
  if (!formRef.value) return false
  try {
    const isValid = await new Promise<boolean>(resolve => {
      formRef.value!.validate((valid, errMessage) => {
        if (!valid) {
          emits('validationError', errMessage)
        }
        resolve(valid)
      })
    })
    const result = isValid ? { formDatas: props.model } : false
    if (props.isQueryArea) {
      emits('search', result)
    }
    return result
  } catch (error) {
    console.error('表单验证出错:', error)
    return false
  }
}
// 重置
const formReset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
    emits('reset')
  }
}
// 暴露属性 供父组件使用
defineExpose({ formSubmit })
</script>
